/* components */
import { ConnectorModuleRuleFormItem } from '@src/modules/connector/components'
/* model */
import { ConnectorFromField, ConnectorModuleComponentNameEnum, ConnectorToField } from '@src/modules/connector/model'
/* scss */
import '@src/modules/connector/components/rule-form/index.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, PropType, provide, ref, CreateElement } from 'vue'
import { CommonComponentInstance } from '@model/VC'
/* types */
import { ConnectorRuleFormItemType } from '@src/modules/connector/types'
/* util */
import { isEmpty } from '@src/util/type'
import { createConnectorRuleFormItem } from '@src/modules/connector/util'
import { t } from '@src/locales'

const FieldSuffixText = `- ${t('common.connector.field')}`

export type ConnectorModuleRuleFormProps = {
  fromFieldList: ConnectorFromField[];
  isShowOperate: boolean;
  toFieldList: ConnectorToField[];
  value: ConnectorRuleFormItemType[];
  fromBizTypeName: string;
  toBizTypeName: string;
  toBizTypeId: string;
  justFixedValue:boolean;
  showHeader:boolean;
  requiredShowDel:boolean;
  showText:boolean;
  validation: boolean;
}

export interface ConnectorModuleRuleFormSetupState {

}

export enum ConnectorModuleRuleFormEmitEventNameEnum {
  Input = 'input',
}

export type ConnectorModuleRuleFormInstance = ComponentInstance & ConnectorModuleRuleFormSetupState
export type ConnectorModuleRuleFormVM = ComponentRenderProxy<ConnectorModuleRuleFormProps> & CommonComponentInstance & ConnectorModuleRuleFormInstance

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorModuleRuleForm,
  emits: [
    ConnectorModuleRuleFormEmitEventNameEnum.Input,
  ],
  props: {
    fromFieldList: {
      type: Array as PropType<ConnectorFromField[]>,
      default: () => ([])
    },
    isShowOperate: {
      type: Boolean as PropType<boolean>,
      default: true
    },
    isSelect: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    toFieldList: {
      type: Array as PropType<ConnectorToField[]>,
      default: () => ([])
    },
    value: {
      type: Array as PropType<ConnectorRuleFormItemType[]>,
      default: () => ([])
    },
    fromBizTypeName: {
      type: String as PropType<string>,
      default: ''
    },
    toBizTypeName: {
      type: String as PropType<string>,
      default: ''
    },
    toBizTypeId: {
      type: String as PropType<string>,
      default: ''
    },
    justFixedValue:{
      type: Boolean as PropType<boolean>,
      default: false
    },
    showHeader:{
      type: Boolean as PropType<boolean>,
      default: true
    },
    requiredShowDel:{
      type: Boolean as PropType<boolean>,
      default: true
    },
    showText:{
      type: Boolean as PropType<boolean>,
      default: false
    },
    isUpdate:{
      type: Boolean as PropType<boolean>,
      default: false
    },
    validation: {
      type: Boolean,
      default: false
    },
    isWiki: {
      type: Boolean,
      default: false
    },
    nodeConfig: {
      type: Object,
      default: () => ({}),
    },
    isMultipleChoose: {
      type: Boolean,
      default: false
    }
  },
  setup(props: ConnectorModuleRuleFormProps, { emit }) {
    let showRoleComponent = ref(true), showOpenCommentComponent = ref(false);
    return {
      showRoleComponent,
      showOpenCommentComponent
    }
  },
  computed: {
    toFieldListMap(): Record<string, ConnectorToField> {
      return (
        this.toFieldList.reduce((prev, current) => {
          prev[current.enName] = current
          return prev
        }, {} as Record<string, ConnectorToField>)
      )
    }
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {
        if(newValue && newValue.length) {

          const field = newValue.find(item=> item?.field?.fieldName === 'allowShare')
          if(field) {
            if(field.value == 1) {
              // 外部 隐藏角色 显示评论是否对外开放
              this.showRoleComponent = false
              this.showOpenCommentComponent = true
            } else {
              // 内部 显示角色 隐藏评论是否对外开放
              this.showRoleComponent = true
              this.showOpenCommentComponent = false
            }
          }
        }
      }
    }
  },
  mounted() {
    this.initiateRuleForm()
  },
  methods: {
    /**
     * @description 初始化规则表单
    */
    initiateRuleForm() {
      // 没有数据则默认添加一个
      if (isEmpty(this.value)) {

        let formItem:any = createConnectorRuleFormItem()
        if(this.justFixedValue)formItem.condition = 'fixedValue';
        this.onValueInputHandler([formItem])
      }

    },
    /**
     * @description 数据变化事件
    */
    onValueInputHandler(value: ConnectorRuleFormItemType[]) {
      this.$emit(ConnectorModuleRuleFormEmitEventNameEnum.Input, value)
    },
    /**
     * @description 删除某一个项事件
    */
    onDeleteRuleFormItemHandler(index: number) {

      // 浅拷贝一份数据
      const value = [...this.value]

      // 根据索引删除
      value.splice(index, 1)

      // 如果删除后没有数据则添加一个
      if (isEmpty(value)) {
        value.push(createConnectorRuleFormItem())
      }

      this.onValueInputHandler(value)

    }
  },
  render(h: CreateElement) {
    return (
      <div class={[ConnectorModuleComponentNameEnum.ConnectorModuleRuleForm, ConnectorModuleComponentNameEnum.ConnectorModuleRuleFormAutoWidth]}>
        {
          this.showHeader &&
            <div class="connector-module-rule-form-header" >

            <div class={["connector-module-rule-form-header-to",this.showText?'connector-module-rule-form-header-to-large':'',this.isUpdate?'connector-module-rule-form-header-to-left-large':'']}>

              <div class="connector-module-rule-form-header-to-name">
                { this.toBizTypeName }
              </div>

              <div class="connector-module-rule-form-header-to-suffix">
                &nbsp;{ FieldSuffixText }
              </div>

            </div>

            {
            this.isSelect && (<div class="connector-module-rule-form-header-operate">
                {t('common.connector.discriminator')}
            </div>)
            }

            <div class="connector-module-rule-form-header-condition">
              {t('common.connector.takeValueMethod')}
            </div>

            <div class="connector-module-rule-form-header-from">

              <div class="connector-module-rule-form-header-from-name">
                { this.fromBizTypeName }
              </div>

              <div class="connector-module-rule-form-header-from-suffix">
                &nbsp;{ FieldSuffixText }
              </div>

            </div>

            </div>
        }


        {this.value.map((item, index) => {
          const isFirst = index === 0
          let show = true, fieldName = item?.field?.fieldName
          // 判断触发器知识库表单是否隐藏 选择角色
          if(fieldName == 'role' && !this.showRoleComponent) {
            show = false
          }
          // 判断触发器知识库表单是否隐藏 评论是否对外开放
          if(fieldName == 'isOpenComment' && !this.showOpenCommentComponent) {
            show = false
          }

          return show && (
            <ConnectorModuleRuleFormItem
              key={item.id}
              value={item}
              isFirst={isFirst}
              isSelect={this.isSelect}
              existFieldList={this.value}
              toFieldList={this.toFieldList}
              toFieldListMap={this.toFieldListMap}
              fromBizTypeName={this.fromBizTypeName}
              fromFieldList={this.fromFieldList}
              isShowOperate={this.isShowOperate}
              toBizTypeId={this.toBizTypeId}
              onDelete={() => this.onDeleteRuleFormItemHandler(index)}
              onInput={this.onValueInputHandler}
              justFixedValue={this.justFixedValue}
              requiredShowDel={this.requiredShowDel}
              showText={this.showText}
              isUpdate={this.isUpdate}
              validation={this.validation}
              isWiki={this.isWiki}
              nodeConfig={this.nodeConfig}
              isMultipleChoose={this.isMultipleChoose}
            />
          )

        })}

      </div>
    )
  }
})
